const gridElement = document.getElementById('grid');
const resetButton = document.getElementById('reset');
const solveButton = document.getElementById('solve');
const solutionElement = document.getElementById('solution');
const size = 5;
let gridState = Array.from({ length: size }, () => Array(size).fill(false));

function createGrid() {
    gridElement.innerHTML = '';
    gridState.forEach((row, rowIndex) => {
        row.forEach((cell, colIndex) => {
            const cellElement = document.createElement('div');
            cellElement.classList.add('cell');
            if (cell) {
                cellElement.classList.add('on'); // 确保只在这里添加 'on'
            }
            cellElement.addEventListener('click', () => toggleLights(rowIndex, colIndex));
            gridElement.appendChild(cellElement);
        });
    });
}

function toggleLights(row, col) {
    const directions = [
        [0, 0], // center
        [-1, 0], // top
        [1, 0], // bottom
        [0, -1], // left
        [0, 1] // right
    ];
    
    directions.forEach(([dx, dy]) => {
        const newRow = row + dx;
        const newCol = col + dy;
        if (newRow >= 0 && newRow < size && newCol >= 0 && newCol < size) {
            gridState[newRow][newCol] = !gridState[newRow][newCol];
        }
    });

    updateGrid();
    checkGameOver();
}

function updateGrid() {
    const cells = document.querySelectorAll('.cell');
    cells.forEach((cell, index) => {
        const row = Math.floor(index / size);
        const col = index % size;
        cell.classList.toggle('on', gridState[row][col]);
    });
}

function checkGameOver() {
    if (gridState.flat().every(cell => !cell)) {
        setTimeout(() => alert('游戏结束！'), 100);
    }
}

function resetGame() {
    gridState = Array.from({ length: size }, () => Array.from({ length: size }, () => Math.random() < 0.5));
    createGrid();
    solutionElement.textContent = ''; // 清空解决方案显示
}

function toggle(state, row, col) {
    const directions = [
        [0, 0],
        [-1, 0],
        [1, 0],
        [0, -1],
        [0, 1]
    ];

    directions.forEach(([dx, dy]) => {
        const newRow = row + dx;
        const newCol = col + dy;
        if (newRow >= 0 && newRow < size && newCol >= 0 && newCol < size) {
            state[newRow][newCol] = !state[newRow][newCol];
        }
    });
}

function isAllOff(state) {
    return state.flat().every(cell => !cell);
}

function backtrack(state, row, col, steps) {
    if (isAllOff(state)) {
        return steps; // 返回点击步骤
    }

    if (col === size) {
        col = 0;
        row++;
    }

    if (row === size) {
        return null; // 到达最后一行仍未解决
    }

    // 不点击当前灯
    const resultWithoutClick = backtrack(state, row, col + 1, steps);
    if (resultWithoutClick) return resultWithoutClick;

    // 点击当前灯
    const newState = state.map(row => row.slice());
    toggle(newState, row, col);
    const resultWithClick = backtrack(newState, row, col + 1, [...steps, [row, col]]);
    return resultWithClick;
}

function solveLights(initialState) {
    const result = backtrack(initialState, 0, 0, []);
    return result || "无解";
}

solveButton.addEventListener('click', () => {
    const solution = solveLights(gridState);
    solutionElement.textContent = solution.map(step => `(${step[0]}, ${step[1]})`).join(' -> ');
});

resetButton.addEventListener('click', resetGame);
document.addEventListener("DOMContentLoaded",function (params) {
    resetGame();
})
